package com.sxh.gateway.config;

import com.alibaba.fastjson.JSON;
import com.sxh.gateway.exception.BaseException;
import com.sxh.gateway.model.UserInfo;
import com.sxh.gateway.utils.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.SignatureException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;
import org.springframework.web.server.ServerWebExchange;

import javax.annotation.PostConstruct;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtUtil jwtUtil;
    @Value("classpath:security-whitelist.properties")
    private Resource whiteListResource;
    private List<String> whiteList;

    @PostConstruct
    public void loadWhiteList() throws IOException {
        whiteList = Files.readAllLines(whiteListResource.getFile().toPath());
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().value();

        if (whiteList.contains(path)) {
            return chain.filter(exchange);
        }
        // 获取请求头中的 Token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization").substring(7);
        // 验证 Token 是否有效，并提取有效信息放在请求中
        if (token != null && jwtUtil.validateToken(token)) {
//            UserInfo userInfo = jwtUtil.parseToken(token);
//            // 构建新的查询参数：添加 userId到原始请求参数中
//            String newQuery = exchange.getRequest().getURI().getQuery();
//            if (newQuery == null) {
//                newQuery = "ownerId=" + userInfo.getUserId();
//            } else {
//                newQuery += "&ownerId=" + userInfo.getUserId();
//            }
//            // 构造新的 URI，包含新增的查询参数
//            URI newUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI())
//                    .replaceQuery(newQuery)
//                    .build()
//                    .encode()
//                    .toUri();
//            // 构建新的 exchange，替换 request 的 URI
//            ServerWebExchange newExchange = exchange.mutate()
//                    .request(exchange.getRequest().mutate().uri(newUri).build())
//                    .build();
//            return chain.filter(newExchange);
            return chain.filter(exchange);
        }
        return buildReturnMono("无效的Token", exchange);
    }
private Mono<Void> buildReturnMono(String error, ServerWebExchange exchange) {
    ServerHttpResponse response = exchange.getResponse();
    String jsonString = JSON.toJSONString(new BaseException(error));
    byte[] bits = jsonString.getBytes(StandardCharsets.UTF_8);
    DataBuffer buffer = response.bufferFactory().wrap(bits);
    response.setStatusCode(HttpStatus.UNAUTHORIZED);
    response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
    return response.writeWith(Mono.just(buffer));
}
    @Override
    public int getOrder() {
        return -100; // 在其他过滤器之前执行
    }
}

